package com.star.security.authentication.usernamepassword;

import com.star.security.authentication.Authentication;
import com.star.security.authentication.AuthenticationProvider;
import com.star.security.exception.AuthenticationException;
import com.star.security.exception.BadCredentialsException;
import com.star.security.user.UserDetails;
import com.star.security.user.UserDetailsService;
import com.star.security.utils.PasswordEncoders;

/**
 * 通过用户名密码验证
 *
 * @author yangzj
 */
public class UsernamePasswordAuthenticationProvider implements AuthenticationProvider {

    private final UserDetailsService userDetailsService;

    public UsernamePasswordAuthenticationProvider(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UserDetails userDetails = userDetailsService.getByUsername(authentication.getPrincipal().toString()
                , authentication.getDetails());
        // 校验密码
        if (!PasswordEncoders.matches(authentication.getCredentials().toString(), userDetails.getPassword())) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        return UsernamePasswordAuthenticationToken.authenticated(userDetails, authentication.getExpiresIn(), authentication.getMultiEndpoint());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
